package com.gm.server.voice.core;

import com.gm.server.voice.core.runable.ReceiveAudio;
import com.gm.server.voice.core.runable.SendAudio;
import com.gm.server.voice.utils.ThreadPool;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Socket;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

@Data
public class VoiceRoom {

    private static final Logger log = LoggerFactory.getLogger(VoiceRoom.class);
    private String roomId;

    private Map<String, Socket> userSocketMap;

    private Map<String, ReceiveAudio> receiveAudioMap;

    private Queue<UserInputStream> userInputStreamQueue;

    private String roomStatus;

    public VoiceRoom(String roomId) {
        this.roomId = roomId;
        userInputStreamQueue = new LinkedBlockingQueue<>(1024); // 队列上限先设置为1024
    }

    public void putUserSocket(String userId, Socket socket) {
        userSocketMap.put(userId, socket);
    }

    public Socket getUserSocket(String userId) {
        return userSocketMap.get(userId);
    }

    public void putReceiveAudio(String userId, Socket socket) {
        ReceiveAudio receiveAudio = new ReceiveAudio(roomId, userId, socket);
        // 将任务添加到线程迟
        ThreadPool.startTask(receiveAudio);
        receiveAudioMap.put(userId, receiveAudio);
    }

    public void putReceiveAudio(String userId, ReceiveAudio receiveAudio) {
        receiveAudioMap.put(userId, receiveAudio);
    }

    public ReceiveAudio getReceiveAudio(String userId) {
        return receiveAudioMap.get(userId);
    }

    // 添加用户输入流
    public void addUserInputStream(UserInputStream userInputStream) {
        userInputStreamQueue.add(userInputStream);
    }

    // 获取队列中的第一个元素
    public UserInputStream getUserInputStream() {
        return userInputStreamQueue.poll();
    }

    // 获取队列大小
    public Integer getQueueSize() {
        return userInputStreamQueue.size();
    }

    // 开启发送线程
    public void startSendVoice() {
        // 房间开启时启动发送线程
        while ("1".equals(roomStatus)) {
            log.info("发送队列数量：[{}]", getQueueSize());
            UserInputStream userInputStream = getUserInputStream();
            if (userInputStream == null) {
                continue;
            }
            userSocketMap.forEach((userId, socket) -> {
                // 开始发送
                if (!userId.equals(userInputStream.getInputUserId())) {
                    SendAudio sendAudio = new SendAudio(socket, userInputStream.getInputStream());
                    ThreadPool.startTask(sendAudio);
                }
            });
        }
    }
}
